package com.tom.config.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * opencms库数据源
 *
 * @author Administrator
 *
 */
@Configuration
@MapperScan(basePackages = "com.tom.mapper.opencms", sqlSessionTemplateRef = "opencmsSqlSessionTemplate")
public class OpenCmsDataSource {

	@Value("${spring.datasource.opencms.url}")
	private String url;

	@Value("${spring.datasource.opencms.username}")
	private String username;

	@Value("${spring.datasource.opencms.password}")
	private String password;

	@Value("${spring.datasource.opencms.driverClassName}")
	private String driverClassName;

	/** 本数据源扫描的mapper路径 */
	static final String MAPPER_LOCATION = "classpath:mapper/opencms/*.xml";

	@Bean(name = "opencms")
	public DataSource opencmsDataSource() {
		return DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(username)
				.password(password).build();
	}

	@Bean(name = "opencmsSqlSessionFactory")
	public SqlSessionFactory opencmsSqlSessionFactory(@Qualifier("opencms") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
		return bean.getObject();
	}

	@Bean("opencmsTransactionManger")
	public DataSourceTransactionManager opencmsTransactionManger(@Qualifier("opencms") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "opencmsSqlSessionTemplate")
	public SqlSessionTemplate opencmsSqlSessionTemplate(@Qualifier("opencmsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
